/*
 * @Author: HX
 * @Date: 2024-12-06 11:02:23
 * @LastEditors: HX
 * @LastEditTime: 2024-12-17 14:37:38
 */
import global from "../core/global.js";
import {
  pickHitAndRay,
  creatRayToHit,
  pickWorldPositionByMouse,
  vec3ToJson,
  vec3ToCarto,
  CartographicToJson,
  jsonToCar3FromDegrees,
} from "../core/common.js";
import { Model } from "../mixins/model.js";
import { Animation } from "../mixins/track-animation.js";
import { TrackedEntity } from "../scene/tracked_entity.js";

let frameActionList = [];

/**
 * @description: 获取无人机
 * @param {*} cb
 * @return {*}
 */
export function getUAVData(UAVID, cb) {
  if (!global.layerList.get(UAVID)) {
    cb && cb();
    return false;
  }
  let UAVModel = global.layerList.get(UAVID).animation.animEntity();
  let carto = vec3ToCarto(UAVModel.transform.position, true);
  let position = CartographicToJson(carto);
  let boundingSphere = Animation._getBoundingVolume({
    id: UAVID,
  }).boundingSphere;
  let UAVSize = boundingSphere.radius * 2 + 5;
  cb && cb({ position, UAVSize });
  return position;
}

/**
 * @description: 调整无人机状态
 * @param {*} msg
 * @return {*}
 */
export function setUAVData(msg) {
  let UAVModel =
    global.layerList.get("UAV_1").model ||
    global.layerList.get("UAV_1").animation.animEntity();
  let UAVData = JSON.parse(msg);
  UAVData.offset &&
    (UAVModel.transform.position = SSmap.Vector3.add(
      UAVModel.transform.position,
      SSmap.Vector3.create(...Object.values(UAVData.offset))
    ));
  UAVData.rotationZ && (UAVModel.transform.rotationZ = UAVData.rotationZ);
}

/**
 * @description: 摄像头矩阵同步模型矩阵并调整
 * @param {*} entity
 * @return {*}
 */
export function viewFollowUAV(entity) {
  let pichAngle = 45; // 倾斜角度
  let entityMatrix = entity.transform.worldMatrix;
  // 获取摄像头差距（模型包围盒直径 + 5m）
  let boundingSphere =
    Animation._getBoundingVolume({ id: entity.tag }).boundingSphere ||
    Model._getBoundingVolume({ id: entity.tag }).boundingSphere;
  let cameraDistance = boundingSphere.radius * 2 + 6;
  // 调整摄像头矩阵
  let rotX = SSmap.Quaternion.fromAxisAndAngle(
    SSmap.Vector3.create(1.0, 0, 0),
    0
  ).toRotationMatrix();
  let rotY = SSmap.Quaternion.fromAxisAndAngle(
    SSmap.Vector3.create(0, 1.0, 0),
    pichAngle
  ).toRotationMatrix();
  let rotZ = SSmap.Quaternion.fromAxisAndAngle(
    SSmap.Vector3.create(0, 0, 1.0),
    -90
  ).toRotationMatrix();
  let rotation = SSmap.Matrix3.multiply(rotX, rotY);
  rotation = SSmap.Matrix3.multiply(rotation, rotZ);
  let pos = SSmap.Vector3.create(
    -(Math.cos((pichAngle * Math.PI) / 180) * cameraDistance - 1.2),
    0,
    Math.sin((pichAngle * Math.PI) / 180) * cameraDistance
  );
  let rotationMat = SSmap.Matrix4.fromRotationTranslation(rotation, pos);
  let followMatrix = SSmap.Matrix4.multiply(entityMatrix, rotationMat);
  // 同步摄像头矩阵
  let camera = GlobalViewer.scene.mainCamera;
  camera.transform.worldMatrix = followMatrix; //中键和右键不可以旋转视角
  // camera.transform.position = followMatrix.translation(); //中键和右键可以旋转视角
  return cameraDistance
}

/**
 * @description: 摄像头位置同步模型位置并y轴偏移
 * @param {*} entity
 * @return {*}
 */
function trachedEntity(entity, distance = 5) {
  const cameraController = window.viewer.scene.mainCamera.cameraController();
  // 获取实体的位置
  let destination = entity.transform.position.toCartesian3();
  // 设置相机基础位置
  let nowHeading = cameraController.heading;
  let nowPitch = cameraController.pitch;
  let nowRoll = cameraController.roll;
  cameraController.setView(
    destination,
    nowHeading,
    nowPitch,
    nowRoll
  )
  // 相机位置做偏移
  // let distance = cameraController.positionWC.distance(entity.transform.position); //当前视角到中心点距离
  // console.log('distance', distance)
  cameraController.moveBackward(distance); //空间距离
}

/**
 * @description: 选择无人机，摄像头跟随无人机
 * @param {*} x
 * @param {*} y
 * @return {*}
 */
export function pickModel(x, y, cb) {
  let cbOpt = null; // 只在这里定义一次 cbOpt
  let HitAndRay = pickHitAndRay(x, y); // 获取射线与交点信息
  let hit = HitAndRay && HitAndRay.hit;
  let ray = HitAndRay && HitAndRay.ray;
  // 获取与点击位置相关的实体
  let tagEntity = getTagEntity(hit);
  if (tagEntity && tagEntity.tag) {
    // 处理无人机的实体
    if (tagEntity.tag.includes("UAV")) {
      cbOpt = handleUAVFrameAction(tagEntity); // 使用 tagEntity 进行处理
    }
    // 处理航线的实体
    else if (tagEntity.tag.includes("airLine")) {
      let point = pickWorldPositionByMouse(x, y);
      let position = vec3ToJson(point);
      cbOpt = handleAirline(tagEntity, hit, ray, position);
    }
  }
  // 删除 hit 和 ray 对象，释放资源
  cleanupResources(hit, ray);
  // 执行回调函数
  if (cb) cb(cbOpt);
}

// 处理航线的逻辑
function handleAirline(tagEntity, hit, ray, position) {
  let cbOpt = null;
  // 进行射线检测，处理更多的信息
  let HitAndRay_More = creatRayToHit(hit.point, ray.direction);
  let hit_more = HitAndRay_More && HitAndRay_More.hit;
  let ray_more = HitAndRay_More && HitAndRay_More.ray;
  if (hit_more) {
    let tagEntity_more = getTagEntity(hit_more);
    // 如果没有找到其他实体或是管道
    if (!tagEntity_more || tagEntity_more.tag.includes("airLine")) {
      cbOpt = {
        tag: tagEntity.tag,
        position,
      };
    }
    // 如果找到了无人机
    else if (tagEntity_more.tag.includes("UAV")) {
      cbOpt = handleUAVFrameAction(tagEntity_more); // 使用 tagEntity 进行处理
    }
    // 删除额外的 hit 和 ray 对象
    cleanupResources(hit_more, ray_more);
  }
  return cbOpt;
}

// 统一的资源清理函数
function cleanupResources(hit, ray) {
  if (hit && hit.delete) hit.delete();
  if (ray && ray.delete) ray.delete();
}

function getTagEntity(hit) {
  if (hit) {
    let stack = [];
    // 获取到无人机实体
    stack.push(hit.entity.parentEntity ? hit.entity.parentEntity : hit.entity);
    // 遍历栈中的实体
    while (stack.length) {
      let entity = stack.pop();
      // 如果实体有 tag 属性，说明找到目标实体
      if (entity && entity.tag && !entity.tag.includes("Root")) {
        return entity;
      }
      // 如果没有找到tag，继续检查父实体
      let parent = entity.parentEntity;
      if (parent) {
        stack.push(parent);
      }
    }
    // 如果遍历完父实体链仍未找到，返回false
    return false;
  }
  return false; // hit 为 null 或 undefined 时直接返回 false
}

export function handleUAVFrameAction(UAVEntity, id) {
  if (id) UAVEntity = global.layerList.get(id).animation.animEntity();
  if (UAVEntity) {
    let tag = UAVEntity.tag;
    let iconModel = global.layerList.get(`${tag}_Icon`).bbEntity;
    if (frameActionList.findIndex((item) => item.id === tag) !== -1) {
      // 取消视角跟随
      deleteFrameAction(tag);
      iconModel.enabled = true;
    } else {
      //监听模型的坐标
      iconModel.enabled = false;
      let UVAFrameAction = new SSmap.FrameAction();
      let cameraDistance = viewFollowUAV(UAVEntity);
      UVAFrameAction.onTriggered(() => {
        let uva = global.layerList.get(tag);
        if (uva && !uva.animation.paused) {
          trachedEntity(UAVEntity, cameraDistance)
        } else {
          deleteFrameAction(tag);
        }
      });
      GlobalViewer.scene.rootEntity.addComponent(UVAFrameAction);
      frameActionList.push({ id: tag, frameAction: UVAFrameAction });
    }
    return { tag: tag };
  }
}

function deleteFrameAction(id) {
  const index = frameActionList.findIndex((item) => item.id === id);
  if (index !== -1) {
    frameActionList[index].frameAction.delete();
    frameActionList[index] = null;
    frameActionList.splice(index, 1); // 从数组中删除该元素
  }
}

export function iconFollowUAV(iconID, UAVID) {
  let frameAction = new SSmap.FrameAction();
  frameAction.onTriggered(() => {
    let icon = global.layerList.get(iconID);
    let uva = global.layerList.get(UAVID);
    if ((uva && !uva.animation.paused) || icon) {
      let iconModel = icon.bbEntity;
      let position = getUAVData(UAVID);
      if (position) {
        position.height += 1;
        position = jsonToCar3FromDegrees(position).toVector3();
        iconModel.position = position;
      }
    } else {
      deleteFrameAction(iconID);
    }
  });
  GlobalViewer.scene.rootEntity.addComponent(frameAction);
  frameActionList.push({ id: iconID, frameAction: frameAction });
}
